package com.dunshanredis.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @description: 数据源切换
 * @author: 李文
 * @create: 2021-08-21 11:48
 **/
@Aspect
@Component
public class RedisAspectAop {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Value("${spring.redis.database:0}")
    private int defaultDataBase;

    @Value("${resar.oneDatabase}")
    private int resarDataBase;



    @Pointcut("execution(public * com.dunshanredis.controller..*.*(..))")
    public void controllerAspect() {
    }


    @Around(value = "controllerAspect()")
    @ConditionalOnBean(SelectableRedisTemplate.class)
    public Object configRedis(ProceedingJoinPoint point) throws Throwable{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //获取头标示
        String header = request.getHeader("dunshan");
        logger.info("===============请求内容===============");
        logger.info("请求地址:" + request.getRequestURL().toString());
        logger.info("请求方式:" + method.getName());
        logger.info("请求类方法头信息:" + header);

        int db = defaultDataBase;
        try {
            if (header != null && header.equals("7dGgroup")) {
                db = resarDataBase;
                logger.info("压测流量："+db);
            } else {
                db = defaultDataBase;
                logger.info("正常流量: "+db);
            }
            RedisSelectSupport.select(db);
            return point.proceed();
        } finally {
            RedisSelectSupport.select(defaultDataBase);
            logger.debug("redis switch {} to {}",defaultDataBase ,db);
        }
    }
}

